package com.ccx.coachsite.task;

import java.net.URLDecoder;
import java.net.URLEncoder;

import org.json.JSONObject;
import android.content.Context;
import com.ccx.coachsite.bus.Account;
import com.ccx.coachsite.bus.AccountMgr;
import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.http.BaseResp;
import com.ccx.coachsite.http.HttpCallBack;
import com.ccx.coachsite.http.HttpErrorDesc;
import com.ccx.coachsite.http.HttpRequest;
import com.ccx.coachsite.http.UrlConfig;
import com.ccx.coachsite.ui.login.LoginHelper;
import com.ccx.coachsite.ui.login.WeiboBase;
import com.ccx.coachsite.util.Log;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.util.StringUtil;

public class RegisterTask extends TaskBase {

	private Account mAccount;
	private Context mContext;

	public RegisterTask(Context context, HttpCallBack<BaseResp> call, Account account) {
		super(call, context);
		mAccount = account;
		mTaskType = TaskType.TaskTypeRegister;
		mContext = context;
	}
	
	protected void onDataParse(String responseString)
	{
		try {
			JSONObject jsonObject = new JSONObject(responseString);
			JSONObject respsonObject = jsonObject.getJSONObject("response");
			if(respsonObject == null)
				return;
			
			mAccount.setUsername(respsonObject.getString("username"));
			mAccount.setOwerIcon(respsonObject.getString("icon"));
			mAccount.setMobile(respsonObject.getString("mobile"));
			mAccount.setUserId(respsonObject.getInt("id"));
			AccountMgr.saveAccountInfo(mContext, mAccount);
			
			if(mAccount.getWeiboType() == 4)
			{
				SharedPreferencesUtil.setValue(mContext,
						SharedKey.Shared_Login_Type, "4");
			}
			else if(mAccount.getWeiboType() >= 1)
			{
				WeiboBase.saveWeiboInfo(mContext, mAccount.getWeiboType(), mAccount.getWeiboId(), mAccount.getWeiboName());
			}
			else
			{
				SharedPreferencesUtil.setValue(mContext,
						SharedKey.Shared_Login_Type, "-1");
			}
			
			
		} catch (Exception e) {
			Log.e(e.getMessage(), e);
		} finally {
		}
	}
	
	public String getUrl()
	{
		int weiboType = mAccount.getWeiboType();
		String baseUrl = "";
		if(weiboType== -1 || weiboType== 4)
		{
			baseUrl = UrlConfig.getUrlByKey(UrlConfig.RegisterUrlKey);
		}
		else if(weiboType == 1)
		{
			baseUrl = UrlConfig.getUrlByKey(UrlConfig.SinaRegisterUrlKey);
		}
		else if(weiboType == 2)
		{
			baseUrl = UrlConfig.getUrlByKey(UrlConfig.QQRegisterUrlKey);
		}
		
		return baseUrl;
	}
	
	@Override
	protected BaseResp doInBackground(Integer... params) {
		HttpRequest request = new HttpRequest(BaseResp.class);
		
		BaseResp resp = new BaseResp();
		try {
			//String url = genUrl(request);
			//resp = request.execute(url);
			
			String filePath = mAccount.getOwerIcon();
			String fileName = null;
			if(!StringUtil.isEmpty(filePath))
				fileName = filePath.substring(filePath.lastIndexOf('/')+1);
			
			request.addParameter("mobile", mAccount.getMobile());
			String userName = URLEncoder.encode(mAccount.getUsername(), "UTF-8");
			String userName1 = URLDecoder.decode(userName);
			String url = getUrl() + "?mobile=" + mAccount.getMobile()
					+"&userType=1&password="+mAccount.getPassword()+"&code="+mAccount.getMVerifyCode()+
					"&username="+userName;
			
			if(!StringUtil.isEmpty(filePath))
				url += "&iconType=1";
			
			if(StringUtil.isEmpty(mAccount.getMVerifyCode()))
			{
				String Imsi = LoginHelper.getMobileIMSI(mContext);
				url += "&imsinum="+Imsi;
			}
			 int weiboType = mAccount.getWeiboType();
			 if(weiboType == 1 || weiboType == 2)
			 {
				 url += "&uid=" + mAccount.getWeiboId();
			 }
			//request.addParameter("username", mAccount.getUsername());
			String res = request.uploadFile(url, mAccount.getOwerIcon(),fileName);
			//request.uploadFile(url, mAccount.getOwerIcon(), mAccount.getOwerIcon());
			//resp = request.execute(url, HttpRequest.HTTP_METHOD_POST, mAccount.getOwerIcon());
			
			/*
			HttpClient client = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			HttpResponse response = null;
			try {
				File f = new File(mAccount.getOwerIcon());
				FileEntity entity = new FileEntity(f, "binary/octet-stream");
				httpPost.setEntity(entity);
				response = client.execute(httpPost);
			} catch (Exception e) {
			System.out.println(e.toString());
			} finally {
			}
			*/
			
			if (res != null) {
				String result = res;
				JSONObject jsonObject = new JSONObject(result);
				String status = jsonObject.getString("code");
				String desc = jsonObject.getString("desc");
				resp.setDesc(desc);
				if(status.equals("200"))
				{
					resp.setResponse(result);
					onDataParse(result);
					resp.setStatus(BaseResp.SUCCESS);
				}
				else
				{
					int statusCode = Integer.parseInt(status);
					HttpErrorDesc.setErrorDesc(statusCode, resp);
					resp.setStatus(BaseResp.ERROR);
				}
			}
		} catch (Exception e) {
			resp.setStatus(BaseResp.ERROR);
			Log.e(e.getMessage(), e);
		} finally {
			request.release();
		}

		return resp;
	}

	@Override
	protected String genUrl(HttpRequest request)
	{
		request.addParameter("mobile", mAccount.getMobile());
		request.addParameter("mobile", mAccount.getMobile());
		String url = UrlConfig.getUrlByKey(UrlConfig.RegisterUrlKey) + "?mobile" + mAccount.getMobile()
				+"&userType=1&password="+mAccount.getPassword()+"&code="+mAccount.getMVerifyCode()+
				"&username="+mAccount.getUsername();
		
		/*
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		HttpResponse response = null;
		try {
			File f = new File(mAccount.getOwerIcon());
			FileEntity entity = new FileEntity(f, "binary/octet-stream");
			httpPost.setEntity(entity);
			response = client.execute(httpPost);
		} catch (Exception e) {
		System.out.println(e.toString());
		} finally {
		}
		*/
		return UrlConfig.getUrlByKey(UrlConfig.RegisterUrlKey);
	}
}
